package com.example.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.Result;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.pojo.dto.LoginDTO;
import com.example.springboot.pojo.dto.UserDTO;
import com.example.springboot.pojo.entity.User;
import com.example.springboot.pojo.vo.UserVO;
import com.example.springboot.service.IUserService;
import com.example.springboot.utils.RedisConstants;
import com.example.springboot.utils.TokenUtils;
import com.example.springboot.utils.UserHolder;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;



    @Autowired
    private UserMapper userMapper;

    @Override
    public Result login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        // 1.查询用户
        User user = userMapper.loginByNameAndPass(username, password);
        // 2.数据库中查不到，返回报错
        if (user == null) {
            return Result.error("用户名或密码错误!");
        }
        // 3.生成token 存入redis 设置过期时间
        String token = TokenUtils.createToken(user.getId().toString(), user.getPassword());
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_TOKEN_KEY + user.getId().toString(),token);
        redisTemplate.expire(RedisConstants.LOGIN_TOKEN_KEY + user.getId(),RedisConstants.LOGIN_TOKEN_TTL,TimeUnit.SECONDS);

        // 4.将登录用户信息存入ThreadLocal中
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        userVO.setToken(token);
        UserHolder.saveUser(userVO);

        // 5.将登录用户信息存入redis中
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_USER_KEY + userVO.getId(),userVO);
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY,RedisConstants.LOGIN_USER_TTL,TimeUnit.SECONDS);

        return Result.success(userVO);
    }

    @Override
    public Result pageUser(Integer pageNum, Integer pageSize, String username, String role) {
        //设置分页数
        PageHelper.startPage(pageNum,pageSize);
        // 自定义查询
        List<User> userList = userMapper.selectByUsernameAndRole(username,role);

        Page page = (Page)userList;

        List result = page.getResult();
        long total = page.getTotal();
        HashMap<String, Object> map = new HashMap<>();
        map.put("result",result);
        map.put("total",total);

        return Result.success(map);
    }

    @Override
    public Result update(User user) {
        userMapper.updateById(user);
        return Result.success();
    }

    @Override
    public Result addUser(User user) {
        // 默认密码 111111
        user.setPassword("111111");
        userMapper.insertUser(user);
        return Result.success();
    }

    @Override
    public Result deleteUser(Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }

    @Override
    public Result deleteUsers(List<Long> ids) {
        userMapper.deleteBatch(ids);
        return Result.success();
    }

    @Override
    public Result logout(String id) {
        redisTemplate.delete(RedisConstants.LOGIN_TOKEN_KEY + id);
        redisTemplate.delete(RedisConstants.LOGIN_USER_KEY + id);
        return Result.success();
    }
}
